#include "myconsole3_networking.h"
#include <QtNetwork>
#include <iostream>
#include "windows.h"
#include "Tools.h"
#include "myconsole1.h"
using namespace  std;

MyConsole3_networking::MyConsole3_networking(QObject *parent)
    : QTcpServer(parent) ,_socket(NULL)
{
}

void MyConsole3_networking::incomingConnection(int socketId)
{
    _socket = new MyConsoleClient(this);
    _socket->setSocketDescriptor(socketId);
    qDebug()<<"incomingConnection\n";

    if(MyConsole1::theInstance){
        MyConsole1::theInstance->start();
    }
}

bool MyConsole3_networking::beginListen(){
    if (!listen(QHostAddress::Any, PORT)) {
        qDebug()<< "Failed to bind to port" << "\n";
        return false;
    }
    qDebug()<< "start listening" << "\n";
    return true;
}

 void MyConsole3_networking::outputString(QString str){
     if(_socket){
         QTextStream ts(_socket);
         ts << str << "\n";
     }else{
         cout << "Waring! No client is connected!" << "\n";
     }
 }

 QString MyConsole3_networking::getInputString(QString str){
     if(_socket){
         QTextStream ts(_socket);
         ts << str ;
     }else{
         cout << "Waring! No client is connected!" << "\n";
     }

     while(!_socket->isReady){
         QTime dieTime = QTime::currentTime().addMSecs(100);
         while( QTime::currentTime() < dieTime )
         QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
     }
     _socket->isReady = false;
     return _socket->getString();
 }

 /////////////////////////////////////////////////////////////////

MyConsoleClient::MyConsoleClient(QObject *parent)
    : QTcpSocket(parent), isReady(false)
{
    connect(this, SIGNAL(readyRead()), this, SLOT(readClient()));
    connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
}

void MyConsoleClient::readClient(){
//    qDebug()<<"readClient\n";
    _str = "";
    while(canReadLine()){
        QString line = readLine();
        line.replace("\n","");
        _str.append(line);
//        cout << "readClient : " << _str.toStdString() << "\n" ;
        isReady = true;
    }
}

